﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
//using System.Xml;

using PowerCreator.LMS.Course.Entity;
using PowerCreator.LMS.Project.Entity;
using PowerCreator.LMS.Common.Script;
using PowerCreator.LMS.Common.Utils;
using PowerCreator.LMS.Web.Course;
using PowerCreator.LMS.Grade.Entity;
using PowerCreator.LMS.Web.Grade;

public partial class Theme_3_OpenPowercreator : PowerCreator.LMS.Web.Base.BasePage
{    
    //更新学习资源，如果没有的参数，则使用0替换,1添加资源访问记录
    protected string _isUpdateCourse = "1";
    protected string _url = "";  //更新课件访问信息URL
    protected string _fileUrl = "";
    protected string _vPowerCreator = "0";   //是否调PowerCreator课件界面,1调用，其它为不调用
    protected string _vNoPowerCreator = "0"; //其它课件类型
    protected string _Position = "0";

    PowerCreator.LMS.Web.Course.Course opCourse = new PowerCreator.LMS.Web.Course.Course();                     //课程管理
    PowerCreator.LMS.Web.Course.Resource opResource = new Resource();
    PowerCreator.LMS.Web.Course.VirtualDirectory opVirtual = new VirtualDirectory();
    string _openhistoryurl = "OpenHistory.aspx?ProjectID={0}&ProjectClassID={1}&ProjectClassUserID={2}&ProjectResourceID={3}&CourseResourceID={4}&ResourceID={5}&ProjectResourceResourceStartTime={6}"; 
    protected string _IsComment = "0";//是否允许评论,0不允许，1允许


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.Title = config.GetLanagerValueByKey("theme_Comment_TitleInfo", PowerCreator.LMS.Language.LanagetItemType.Page);
            InitPage();

            BinderUserLogin();
            btn_out.Text = config.GetLanagerValueByKey("SignOut", PowerCreator.LMS.Language.LanagetItemType.WebTitle);

            string projectid = Request.QueryString["ProjectID"].ToString();
            ViewState["ProjectID"] = projectid;
            string projectclassid = Request.QueryString["ProjectClassID"].ToString();
            ViewState["ProjectClassID"] = projectclassid;
            string projectresourceid = Request.QueryString["ProjectResourceID"].ToString();
            ViewState["ProjectResourceID"] = projectresourceid;
            string courseresourceid = Request.QueryString["CourseResourceID"].ToString();
            ViewState["CourseResourceID"] = courseresourceid;
            string resourceid = Request.QueryString["ResourceID"].ToString();
            ViewState["ResourceID"] = resourceid;
            string courseID = Request.QueryString["CourseID"].ToString();
            ViewState["CourseID"] = courseID;

            BinderPage();
        }
    }



    protected void lnkbtn_EN_Click(object sender, EventArgs e)
    {
        Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_LANGEID] = "1";
    }
    protected void lnkbtn_CN_Click(object sender, EventArgs e)
    {
        Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_LANGEID] = "0";
    }
    protected void BinderUserLogin()
    {
        if (Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO] == null)
        {
            lal_UserLogin.Text = "<a  href=\"UserLogin.aspx\">" + config.GetLanagerValueByKey("SysManagerLogin", PowerCreator.LMS.Language.LanagetItemType.Page) + "</a> |  <a  href=\"Register.aspx\">" + config.GetLanagerValueByKey("SysManagerRegistor", PowerCreator.LMS.Language.LanagetItemType.Page) + "</a>";
            btn_out.Visible = false;
        }
        else
        {
            PowerCreator.LMS.Web.User.LoginEntity login = (PowerCreator.LMS.Web.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
            lal_UserLogin.Text = login.AccountInfo.RealName.Trim() + "," + config.GetLanagerValueByKey("Login_msg_code5", PowerCreator.LMS.Language.LanagetItemType.Page) + "！| ";
            btn_out.Visible = true;
        }
    }
    protected void btn_out_Click(object sender, EventArgs e)
    {
        PowerCreator.LMS.Web.User.User opUser = new PowerCreator.LMS.Web.User.User();
        //opUser.UpdateOnlineUserByUserID(GetLoginEntity.UserID);
        Session.Abandon();
        PowerCreator.LMS.Common.Script.Script.ReloadMe();
    }




    private void BinderPage()
    {
        VOTResource vo = opCourse.LoadResource(int.Parse(ViewState["ResourceID"].ToString()));

        //获取资源的详细信息
        _fileUrl = WebUtils.WebRoot + vo.ResourceUrl + vo.ResourceEntry;

        //首先判断文件是否存在，不存在即退出
        if (!System.IO.File.Exists(Server.MapPath(_fileUrl)))
        {
            Script.ShowAndCloseMe(this,"文件不存在，请联系管理员！");
            //Response.End();
        }

        //判断课件的类型，根据不同的类型做不同的处理
        switch (vo.ResourceClass)
        {
            case 1:
                OpenPowerCreatorCourseWare(vo);
                break;
            case 2:
                OpenVideo(vo);
                break;
            case 3:
                OpenDownload(vo);
                break;
            case 4:
                OpenNoPowerCreator(vo);
                break;
            case 5:
                OpenWebCourseware(vo);
                break;
        }

        //记录用户学习记录
        SetOpenHistoryUrl();

        //课件点播次数加1
        vo.ResourceClickNum += 1;
        vo.ResourceLastVisitTime = DateTime.Now;
        opCourse.UpdateResource(vo);
    }




    //打开普通的翰博尔课件
    private void OpenPowerCreatorCourseWare(VOTResource vo)
    {
        //检查课件是否是第一次被点播，如果是第一次被点播，则修改remoteclip.asx文件。
        if (!vo.ResourceMmsUpdateState)
        {
            int courseID=opCourse.LoadCourseResource(int.Parse(ViewState["CourseResourceID"].ToString())).FKCourseresCourseID;
            int virID=opCourse.LoadVOTCourse(courseID).FKCourseVirId;
            opResource.UpdataResourceByEditMMS(vo);

        }

        _Position = GetPosition();
        //是否使用微格功能
        string parentList = string.Format("ProjectID={0}&ClassID={1}&UserID={2}&ProjectResourceID={3}&CoursResourceID={4}&ResourceID={5}&Position={6}&CourseID={7}",ViewState["ProjectID"], ViewState["ProjectClassID"], GetLoginEntity.UserID, ViewState["ProjectResourceID"], ViewState["CourseResourceID"], ViewState["ResourceID"], _Position, ViewState["CourseID"]);
        if (PowerCreator.LMS.Web.Config.WebConfig.IsUseWeGe)
        {
            //Script.RedirectURL(WebUtils.WebRoot + "/web/UserObject/OpenCourseWareCommentNew123.aspx?" + parentList);
            Script.RedirectURL("openCourseWareCommentNew.aspx?" + parentList);
        }

        //_fileUrl = "../Single/content.aspx?fileUrl=" + vo.ResourceUrl ;
        _fileUrl = string.Format("../Single/content.aspx?rsd={0}",  ViewState["ResourceID"]);
        _vPowerCreator = "1";
        pl_PowerCreaotr.Visible = true;
        pl_Video.Visible = false;
        pl_Download.Visible = false;
        pl_NoPowercreator.Visible = false;
    }
    //打开纯视频文件
    private void OpenVideo(VOTResource vo)
    {
        _vPowerCreator = "0";

        //是否使用微格功能
        _Position = GetPosition();

        string parentList = string.Format("ProjectID={0}&ClassID={1}&UserID={2}&ProjectResourceID={3}&CoursResourceID={4}&ResourceID={5}&Position={6}&CourseID={7}", ViewState["ProjectID"], ViewState["ProjectClassID"], GetLoginEntity.UserID, ViewState["ProjectResourceID"], ViewState["CourseResourceID"], ViewState["ResourceID"], _Position, ViewState["CourseID"]);
        if (PowerCreator.LMS.Web.Config.WebConfig.IsUseWeGe)
        {
            Script.RedirectURL("openCourseWareCommentNew.aspx?" + parentList);
        }

        _fileUrl = string.Format("../Video/OpenVideo.aspx?rsd={0}", ViewState["ResourceID"]);


        pl_PowerCreaotr.Visible = false;
        pl_Video.Visible = true;
        pl_Download.Visible = false;
        pl_NoPowercreator.Visible = false;
    }
    //打开下载文件
    private void OpenDownload(VOTResource vo)
    {
        _vPowerCreator = "0";
        //绑定界面数据
        lbl_CreatedTime.Text = vo.ResourceCreatedTime.ToString("yyyy/MM/dd");
        lbl_DownloadCount.Text = vo.ResourceClickNum.ToString();
        lbl_LastTime.Text = vo.ResourceLastVisitTime.ToString("yyyy/MM/dd");
        lbl_ResourceName.Text = vo.ResourceName;
        li_Description.Text = vo.ResourceDescription;
        hyplnk_FileUrl.NavigateUrl = _fileUrl;
        hyplnk_ImgFileurl.NavigateUrl = _fileUrl;
        //hyplnk_ImgFileurl.Target = "_";
        pl_PowerCreaotr.Visible = false;
        pl_Video.Visible = false;
        pl_Download.Visible = true;
        pl_NoPowercreator.Visible = false;
    }
    //打开其他课件
    private void OpenNoPowerCreator(VOTResource vo)
    {
        _fileUrl = WebUtils.WebRoot + vo.ResourceUrl + vo.ResourceEntry;
        _vPowerCreator = "0";
        _vNoPowerCreator = "1";
        pl_NoPowercreator.Visible = true;
        pl_PowerCreaotr.Visible = false;
        pl_Video.Visible = false;
        pl_Download.Visible = false;
    }
    //打开外部链接课件
    private void OpenWebCourseware(VOTResource vo)
    {
        _fileUrl = vo.ResourceUrl + vo.ResourceEntry;
        _vPowerCreator = "0";
        _vNoPowerCreator = "1";
        pl_NoPowercreator.Visible = true;
        pl_PowerCreaotr.Visible = true;
        pl_Video.Visible = false;
        pl_Download.Visible = false;
    }

    private string GetPosition()
    {
        string position = "0";
        string search = " select top 1 SscrlogCurrentPosition  from TStudentStudyCouReslog where FKSscrlogTrainproID=" + ViewState["ProjectID"].ToString() + "  and FKSscrlogUserID=" + GetLoginEntity.UserID + " and FKSscrlogResourceID=" + ViewState["ResourceID"].ToString() + " order by SscrlogID desc";
        PowerCreator.LMS.ViewQuery.ViewQuery opViewQuery = new PowerCreator.LMS.ViewQuery.ViewQuery();
        DataTable dt = opViewQuery.Query(search, 1, 1);

        if (dt.Rows.Count == 1)
        {
            position = dt.Rows[0][0].ToString();
        }
        return position;
            
    }

    private void SetOpenHistoryUrl()
    {
        _url = string.Format(_openhistoryurl, ViewState["ProjectID"], ViewState["ProjectClassID"].ToString(), GetLoginEntity.UserID.ToString(), ViewState["ProjectResourceID"], ViewState["CourseResourceID"], ViewState["ResourceID"], DateTime.Now.ToString());
        //_isUpdateCourse = "1";
    }
    protected override void InitPage()
    {
        base.InitPage();
    }

    protected void imgbtn_FileDown_Click(object sender, ImageClickEventArgs e)
    {
        VOTResource vo = opCourse.LoadResource(int.Parse(ViewState["ResourceID"].ToString()));

        _fileUrl = WebUtils.WebRoot + vo.ResourceUrl + vo.ResourceEntry;
        string path = Server.MapPath(_fileUrl);

        if (System.IO.File.Exists(path))
        {
            try
            {
                //打开要下载的文件
                System.IO.FileStream r = new System.IO.FileStream(path, System.IO.FileMode.Open);
                //设置基本信息
                Response.Buffer = false;
                Response.AddHeader("Connection", "Keep-Alive");
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + System.IO.Path.GetFileName(path));
                Response.AddHeader("Content-Length", r.Length.ToString());
                while (true)
                {
                    //开辟缓冲区空间
                    byte[] buffer = new byte[1024];
                    //读取文件的数据
                    int leng = r.Read(buffer, 0, 1024);
                    if (leng == 0)//到文件尾，结束
                        break;
                    if (leng == 1024)//读出的文件数据长度等于缓冲区长度，直接将缓冲区数据写入
                        Response.BinaryWrite(buffer);
                    else
                    {
                        //读出文件数据比缓冲区小，重新定义缓冲区大小，只用于读取文件的最后一个数据块
                        byte[] b = new byte[leng];
                        for (int i = 0; i < leng; i++)
                            b[i] = buffer[i];
                        Response.BinaryWrite(b);
                    }
                }
                r.Close();//关闭下载文件
                Response.End();//结束文件下载
            }
            catch (Exception ex)
            {
                BaseWriteLog(ex.Message);
                lab_err.Text = "文件下载出现意外，请联系管理员!异常描述：" + ex.Message;
            }

            if (!opCourse.UpdateResource(vo))
            {
                lab_err.Text = "注意：程序出现意外，请联系管理员！";
            }
        }
        else
        {
            lab_err.Text = "注意：文件不存在，请联系管理员！";
        }
    }


    //private void ReadFile(string filepath)
    //{
    //    XmlTextReader reader=new XmlTextReader(filepath);
    //    reader.WhitespaceHandling=WhitespaceHandling.None;
    //    XmlDocument xmlDoc=new XmlDocument();
    //    //将文件加载到XmlDocument对象中
    //    xmlDoc.Load(reader);
    //    //关闭连接
    //    reader.Close();

    //    XmlNode xnod = xmlDoc.DocumentElement;
    //    XmlNode xnodWorking; 
    //    if (xnod.Name == "DOCUMENT")
    //    {
    //        //如果还有子节点，就递归地调用这个程序
    //        if (xnod.HasChildNodes)
    //        {
    //            xnodWorking = xnod.FirstChild;
    //            while (xnodWorking != null)
    //            {
    //                if (xnodWorking.Name == "DATETIME")
    //                {
    //                    string time = xnodWorking.FirstChild.Value;
    //                    _starttime = DateTime.Parse(time);
    //                }
    //                else if (xnodWorking.Name == "GUID")
    //                {
    //                    _guid = xnodWorking.FirstChild.Value;
    //                }
    //                else if (xnodWorking.Name == "DURATION")
    //                {
    //                    _videotime = xnodWorking.FirstChild.Value;
    //                }
    //                xnodWorking = xnodWorking.NextSibling;
    //            }
    //        }
    //    }
    //}

    //private void UpdateGradeResourceID(int ResourceID)
    //{
    //    VOTGrade vo = new VOTGrade();
    //    GradeManager opGrade = new GradeManager();
    //    DataTable dt = new DataTable();
    //    string sql = "FKGradeContentGuid='" + _guid + "' and FKGradeResourceID is null";
    //    dt = opGrade.QueryGrade(sql);
    //    if (dt.Rows.Count > 0)
    //    {
    //        for (int i = 0; i < dt.Rows.Count; i++)
    //        {
    //            vo.GradeID = int.Parse(dt.Rows[i]["GradeID"].ToString());
    //            vo.GradeScore=int.Parse(dt.Rows[i]["GradeScore"].ToString());
    //            vo.GradeContent=dt.Rows[i]["GradeContent"].ToString();
    //            vo.FKGradeSkillID=int.Parse(dt.Rows[i]["FKGradeSkillID"].ToString());
    //            vo.FKGradeContentGuid=dt.Rows[i]["FKGradeContentGuid"].ToString();
    //            vo.GradeCreatetime=DateTime.Parse(dt.Rows[i]["GradeCreatetime"].ToString());
    //            vo.FKGradeUserID = int.Parse(dt.Rows[i]["FKGradeUserID"].ToString());
    //            //修改FKGradeResourceID
    //            vo.FKGradeResourceID = ResourceID;
    //            //根据参数starttime即开始录课时间以及记录中的GradeCreatetime即记录产生时间计算出记录产生时视频的时间点，然后记录到数据表的GradeAsfTime字段中
    //            if (vo.GradeCreatetime != null)
    //            {
    //                TimeSpan ts = PowerCreator.LMS.Common.Utils.TimeUtils.TimeCompart(_starttime, vo.GradeCreatetime);
    //                vo.GradeAsfTime =int.Parse((ts.Ticks/10000000).ToString());
    //            }
    //            opGrade.UpdateGrade(vo);
    //        }
    //    }
    //}

    //private void UpdateResourceVideotime(int ResourceID)
    //{
    //    VOTResource vo = new VOTResource();
    //    string sql = "ResourceID=" + ResourceID;
    //    vo = opCourse.LoadResource(ResourceID);
    //    string[] str = _videotime.Split(':');
    //    int videotime = 0;
    //    if (str.Length == 3)
    //    {
    //        if (int.Parse(str[0]) > 0)
    //            videotime = int.Parse(str[0]) * 60;
    //        videotime = videotime + int.Parse(str[1]);
    //    }
    //    vo.ResourceVideoTime = videotime;
    //    opCourse.UpdateResource(vo);
    //}


}
